<template>  
  <div class="app-appNews-edit">
    <!-- 添加或修改文章对话框 -->
    <el-dialog v-model="isShowDialog" width="1000px" :close-on-click-modal="false" :destroy-on-close="true">
      <template #header>
        <div v-drag="['.app-appNews-edit .el-dialog', '.app-appNews-edit .el-dialog__header']">{{(!formData.id || formData.id==0?'添加':'修改')+'文章'}}</div>
      </template>
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="120px">        
        <el-form-item label="分类" prop="categoryId">          
          <el-cascader
                  v-model="formData.categoryId"
                  placeholder="请选择"
                  :options="categoryIdOptions"
                  filterable
                  clearable
                  :props="{ label: 'cateName',value: 'id',checkStrictly: true,emitPath: false  }"
          />
        </el-form-item>        
        <el-form-item label="标题" prop="title">
          <el-input v-model="formData.title" placeholder="请输入标题" />
        </el-form-item>        
        <el-form-item label="作者" prop="author">
          <el-input v-model="formData.author" placeholder="请输入作者" />
        </el-form-item>        
        <el-form-item label="缩略图" prop="thumb">
          <el-upload
            v-loading="upLoadingThumb"
            :action="baseURL+'api/v1/system/upload/singleImg'"
            :before-upload="beforeAvatarUploadThumb"
            :data="setUpData()"
            :on-success="handleAvatarSuccessThumb"
            :show-file-list="false"
            class="avatar-uploader"
            name="file"
          >
            <img v-if="!proxy.isEmpty(imageUrlThumb)" :src="imageUrlThumb" class="avatar">
            <el-icon v-else class="avatar-uploader-icon"><ele-Plus /></el-icon>
          </el-upload>
        </el-form-item>        
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio
              v-for="dict in statusOptions"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>        
        <el-form-item label="内容">
          <gf-ueditor editorId="ueAppNewsContent" v-model="formData.content" @setEditContent="setContentEditContent"></gf-ueditor>
        </el-form-item>       
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="onSubmit" :disabled="loading">确 定</el-button>
          <el-button @click="onCancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts">
import { reactive, toRefs, defineComponent,ref,unref,getCurrentInstance } from 'vue';
import {ElMessageBox, ElMessage, FormInstance,UploadProps} from 'element-plus';
import {
  listAppNews,
  getAppNews,
  delAppNews,
  addAppNews,
  updateAppNews,  
} from "/@/api/app/appNews";
import GfUeditor from "/@/components/ueditor/index.vue"
import {getToken} from "/@/utils/gfast"
import {
  AppNewsTableColumns,
  AppNewsInfoData,
  AppNewsTableDataState,
  AppNewsEditState
} from "/@/views/app/appNews/list/component/model"
export default defineComponent({
  name:"ApiV1AppAppNewsEdit",  
  components:{    
    GfUeditor,    
  },  
  props:{    
    categoryIdOptions:{
      type:Array,
      default:()=>[]
    },    
    statusOptions:{
      type:Array,
      default:()=>[]
    },    
  },  
  setup(props,{emit}) {    
    const baseURL:string|undefined|boolean = import.meta.env.VITE_API_URL    
    const {proxy} = <any>getCurrentInstance()
    const formRef = ref<HTMLElement | null>(null);
    const menuRef = ref();    
    //图片上传地址
    const imageUrlThumb = ref('')
    //上传加载
    const upLoadingThumb = ref(false)    
    const state = reactive<AppNewsEditState>({
      loading:false,
      isShowDialog: false,
      formData: {        
        id: undefined,        
        categoryId: undefined,        
        title: undefined,        
        author: undefined,        
        thumb: undefined,        
        status: false ,        
        hits: undefined,        
        content: undefined,        
        createdAt: undefined,        
        updatedAt: undefined,        
        deletedAt: undefined,        
        linkedAppNewsAppNewsCategory: {          
          id:undefined,    // ID          
          cateName:undefined,    // 名称          
        },        
      },
      // 表单校验
      rules: {        
      }
    });
    // 打开弹窗
    const openDialog = (row?: AppNewsInfoData) => {
      resetForm();
      if(row) {
        getAppNews(row.id!).then((res:any)=>{
          const data = res.data;          
          data.categoryId = parseInt(data.categoryId)          
          //单图地址赋值
          imageUrlThumb.value = data.thumb ? proxy.getUpFileUrl(data.thumb) : ''          
          data.status = ''+data.status          
          state.formData = data;
      })
    }
      state.isShowDialog = true;
    };
    // 关闭弹窗
    const closeDialog = () => {
      state.isShowDialog = false;
    };
    // 取消
    const onCancel = () => {
      closeDialog();
    };
    // 提交
    const onSubmit = () => {
      const formWrap = unref(formRef) as any;
      if (!formWrap) return;
      formWrap.validate((valid: boolean) => {
        if (valid) {
          state.loading = true;
          if(!state.formData.id || state.formData.id===0){
            //添加
          addAppNews(state.formData).then(()=>{
              ElMessage.success('添加成功');
              closeDialog(); // 关闭弹窗
              emit('appNewsList')
            }).finally(()=>{
              state.loading = false;
            })
          }else{
            //修改
          updateAppNews(state.formData).then(()=>{
              ElMessage.success('修改成功');
              closeDialog(); // 关闭弹窗
              emit('appNewsList')
            }).finally(()=>{
              state.loading = false;
            })
          }
        }
      });
    };
    const resetForm = ()=>{
      state.formData = {        
        id: undefined,        
        categoryId: undefined,        
        title: undefined,        
        author: undefined,        
        thumb: undefined,        
        status: false ,        
        hits: undefined,        
        content: undefined,        
        createdAt: undefined,        
        updatedAt: undefined,        
        deletedAt: undefined,        
        linkedAppNewsAppNewsCategory: {          
          id:undefined,    // ID          
          cateName:undefined,    // 名称          
        },        
      }      
      imageUrlThumb.value = ''      
    };    
    //单图上传缩略图
    const handleAvatarSuccessThumb:UploadProps['onSuccess'] = (res, file) => {
      if (res.code === 0) {
        imageUrlThumb.value = URL.createObjectURL(file.raw!)
        state.formData.thumb = res.data.path
      } else {
        ElMessage.error(res.msg)
      }
      upLoadingThumb.value = false
    }
    const beforeAvatarUploadThumb = () => {
      upLoadingThumb.value = true
      return true
    }    
    const setUpData = () => {
      return { token: getToken() }
    }    
    //富文本编辑器内容
    const setContentEditContent = (data:string) => {
      state.formData.content = data
    }    
    return {
      proxy,
      openDialog,
      closeDialog,
      onCancel,
      onSubmit,
      menuRef,
      formRef,      
      //图片上传地址
      imageUrlThumb,
      //上传加载
      upLoadingThumb,
      handleAvatarSuccessThumb,
      beforeAvatarUploadThumb,      
      setUpData,      
      //富文本编辑器内容
      setContentEditContent,      
      baseURL,      
      ...toRefs(state),
    };
  }
})
</script>
<style scoped>  
  .app-appNews-edit :deep(.avatar-uploader .avatar) {
    width: 178px;
    height: 178px;
    display: block;
  }
  .app-appNews-edit :deep(.avatar-uploader .el-upload) {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }
  .app-appNews-edit :deep(.avatar-uploader .el-upload:hover) {
    border-color: var(--el-color-primary);
  }
  .app-appNews-edit :deep(.el-icon.avatar-uploader-icon) {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
  }  
  .kv-label{margin-bottom: 15px;font-size: 14px;}
  .mini-btn i.el-icon{margin: unset;}
  .kv-row{margin-bottom: 12px;}
</style>